package com.yj.springbootdynamic.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;

@Configuration
public class DynamicDBConfig {


    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource master(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slaver")
    public DataSource slaver(){
        return DataSourceBuilder.create().build();
    }


    @Bean
    public DataSourceRouter dynamicDB(DataSource master, DataSource slaver){
        DataSourceRouter dataSourceRouter = new DataSourceRouter();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("master",master);
        map.put("slaver",slaver);

        dataSourceRouter.setTargetDataSources(map);
        dataSourceRouter.setDefaultTargetDataSource(master);
        return dataSourceRouter;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSourceRouter dynamicDB) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("mapper/*.xml"));
        sqlSessionFactoryBean.setDataSource(dynamicDB);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory){
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        return sqlSessionTemplate;
    }


}
